
/* components */
import { 
  SettingGPTViewContent,
  SettingGPTViewDialog
} from "@src/modules/setting/gpt/components"
import SettingGPTSettingViewRobotTable from "@src/modules/setting/gpt/views/index/table"
import SettingGPTSettingViewRobotOperate from "@src/modules/setting/gpt/views/index/operate"
import SettingGPTRobotViewName from "@src/modules/setting/gpt/views/index/name"
import SettingGPTRobotViewUrlDescriptionDialog from "@src/modules/setting/gpt/views/home/url-description-dialog"
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum"
/* hooks */
import { useBSHSettingGPTRobotList } from "@src/modules/setting/gpt/hooks"
/* model */
import { SettingGPTRobotListFields } from "@src/modules/setting/gpt/model"
import LoginUser from "@model/entity/LoginUser/LoginUser"
/* vue */
import { defineComponent } from "vue"
import { PropType } from "vue/types/v3-component-props"
/* types */
import Column from "@model/types/Column"
import { SettingGPTConfigType, SettingGPTRobotType } from "@src/modules/setting/gpt/types"
/* scss */
import "@src/modules/setting/gpt/views/home/list.scss"
/* util */
import platform from "@src/platform"
import { isRobotSystem, settingListFieldsToColumns } from "@src/modules/setting/gpt/utils"
import { isFalsy } from "@src/util/type"
import { openTabGptRobotEdit } from "@src/util/business/openTab"
import { getRootWindow } from "pub-bbx-utils"
import { getRootWindowInitData } from "@src/util/window"

type SettingGPTViewDialogComponentType = InstanceType<typeof SettingGPTViewDialog>
type SettingGPTRobotViewNameComponentType = InstanceType<typeof SettingGPTRobotViewName>
type SettingGPTRobotViewUrlDescriptionDialogComponentType = InstanceType<typeof SettingGPTRobotViewUrlDescriptionDialog>

enum SettingGPTHomeViewRobotListEventEnum {
  ChangeCommonModel = 'changeCommonModel',
  ChangeModuleList = 'changeModuleList'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTHomeViewRobotList,
  emits: [
    SettingGPTHomeViewRobotListEventEnum.ChangeCommonModel,
    SettingGPTHomeViewRobotListEventEnum.ChangeModuleList
  ],
  props: {
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    setting: {
      type: Object as PropType<SettingGPTConfigType>,
      default: () => ({})
    },
    onChangeCommonModel: {
      type: Function
    },
    onChangeModuleList: {
      type: Function
    }
  },
  setup(props, { emit }) {
    
    const { 
      initialize, 
      gptRobotList, 
      gptRobotPage,
      loading,
      onCreateGPTRobotHandler,
      onUpdateGPTRobotNameHandler,
      onDeleteGPTRobotHandler,
      onToggleHandler
    } = useBSHSettingGPTRobotList()
    
    return {
      initialize,
      onCreateGPTRobotHandler,
      onUpdateGPTRobotNameHandler,
      onDeleteGPTRobotHandler,
      onToggleHandler,
      loading,
      gptRobotList,
      gptRobotPage
    }
    
  },
  data() {
    return {
      isCreate: false,
      nameValue: '',
      currentEditRow: {} as SettingGPTRobotType
    }
  },
  computed: {
    attrs(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ]
      }
    },
    columns(): Column[] {
      return settingListFieldsToColumns(SettingGPTRobotListFields)
    },
    loginUser(): LoginUser {
      const rootWindowInitData = getRootWindowInitData()
      return rootWindowInitData.user || {}
    },
    loginUserAuth(): Record<string, any> {
      return this.loginUser?.auth || {}
    },
    isAllowEdit(): boolean {
      return Boolean(this.loginUserAuth?.XIAOBAO_GPT_EDIT)
    },
    isEdit(): boolean {
      return isFalsy(this.isCreate)
    },
    dialogTitle(): string {
      return this.isEdit ? '编辑机器人' : '添加机器人'
    },
    settingGPTViewDialogComponent(): SettingGPTViewDialogComponentType {
      return this.$refs.SettingGPTViewDialog as SettingGPTViewDialogComponentType
    },
    settingGPTRobotViewNameComponent(): SettingGPTRobotViewNameComponentType {
      return this.$refs.SettingGPTRobotViewName as SettingGPTRobotViewNameComponentType
    },
    settingGPTViewUrlDescriptionDialogComponent(): SettingGPTRobotViewUrlDescriptionDialogComponentType {
      return this.$refs.SettingGPTRobotViewUrlDescriptionDialog as SettingGPTRobotViewUrlDescriptionDialogComponentType
    },
    isRobotLengthLimit(): boolean {
      return this.gptRobotList.length < 10
    },
    isShowAdd(): boolean {
      return this.isAllowEdit && this.isRobotLengthLimit
    }
  },
  mounted() {
    this.initialize()
  },
  methods: {
    descriptionButtonClickHandler() {
      platform.openLink('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/eka8tf9wv8x43arx/xgs8aywpqgn7ymug.html')
    },
    commonModelSwitchChangeHandler(value: boolean) {
      this.onChangeCommonModelHandler(value)
    },
    moduleListChangeHandler(value: string[]) {
      this.onChangeModuleListHandler(value)
    },
    openDialog() {
      this.settingGPTViewDialogComponent.open()
      this.settingGPTRobotViewNameComponent.clearValidate()
    },
    closeDialog() {
      this.settingGPTViewDialogComponent.close()
    },
    onChangeCommonModelHandler(value: boolean) {
      this.$emit(SettingGPTHomeViewRobotListEventEnum.ChangeCommonModel, value)
    },
    onChangeModuleListHandler(value: string[]) {
      this.$emit(SettingGPTHomeViewRobotListEventEnum.ChangeModuleList, value)
    },
    onInputGPTRobotNameHandler(value: string) {
      this.nameValue = value
    },
    onClearGPTRobotNameHandler() {
      this.settingGPTRobotViewNameComponent.clear()
    },
    onCreateHandler() {
      this.nameValue = ''
      this.setIsCreateTrue()
      this.openDialog()
    },
    onEditHandler(row: SettingGPTRobotType) {
      this.currentEditRow = row
      this.nameValue = row.name
      this.setIsCreateFalse()
      this.openDialog()
    },
    onSettingHandler(row: SettingGPTRobotType) {
      const id = row.id
      const name = row.name
      openTabGptRobotEdit(id, name)
    },
    onDeleteHandler(row: SettingGPTRobotType) {
      this.onDeleteGPTRobotHandler(row)
    },
    onSwitchHandler(data: { row: SettingGPTRobotType, value: number }) {
      
      const { row, value } = data
      this.onToggleHandler(row, value).then(isSuccess => {
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        // 如果是系统机器人，则需要刷新机器人列表
        const isSystem = isRobotSystem(row)
        if (isSystem) {
          const rootWindow = getRootWindow()
          rootWindow.getRobotList()
        }
        
      })
      
    },
    async onConfirmHandler() {
      
      const validated = await this.settingGPTRobotViewNameComponent.validate()
      
      if (isFalsy(validated)) {
        return
      }
      
      if (this.isEdit) {
        this.onUpdateGPTRobotNameHandlerImpl()
        return
      }
      
      this.onCreateGPTRobotHandlerImpl()
      
    },
    onCreateGPTRobotHandlerImpl() {
      
      const params = {
        name: this.nameValue
      }
      
      this.onCreateGPTRobotHandler(params).then(data => {
        
        const { isSuccess, robotId, name } = data
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        this.onClearGPTRobotNameHandler()
        this.closeDialog()
        openTabGptRobotEdit(robotId, name)
        
      })
    },
    onUpdateGPTRobotNameHandlerImpl() {
      
      const params = {
        name: this.nameValue,
        id: this.currentEditRow.id
      }
      
      this.onUpdateGPTRobotNameHandler(params).then((isSuccess) => {
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        this.onClearGPTRobotNameHandler()
        this.closeDialog()
        
      })
      
    },
    openUrlDescriptionDialog() {
      this.settingGPTViewUrlDescriptionDialogComponent.openDialog()
    },
    setIsCreate(value: boolean) {
      this.isCreate = value
    },
    setIsCreateTrue() {
      this.setIsCreate(true)
    },
    setIsCreateFalse() {
      this.setIsCreate(false)
    },
    renderCommonModelSwitch() {
      return (
        <el-switch
          disabled={this.disabled}
          value={this.setting.useCommonModel}
          onChange={this.commonModelSwitchChangeHandler}
        >
        </el-switch>
      )
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTHomeViewRobotList}>
        
        <SettingGPTViewContent
          {...this.attrs}
        >
          
          <SettingGPTSettingViewRobotOperate
            onAdd={this.onCreateHandler}
            isShowAdd={this.isShowAdd}
          >
          </SettingGPTSettingViewRobotOperate>
          
          <SettingGPTSettingViewRobotTable
            columns={this.columns}
            value={this.gptRobotList}
            isAllowEdit={this.isAllowEdit}
            onDelete={this.onDeleteHandler}
            onEdit={this.onEditHandler}
            onSetting={this.onSettingHandler}
            onSwitch={this.onSwitchHandler}
            onUrlDescriptionDialog={this.openUrlDescriptionDialog}
          >
          </SettingGPTSettingViewRobotTable>
          
        </SettingGPTViewContent>
        
        <SettingGPTViewDialog
          ref="SettingGPTViewDialog"
          title={this.dialogTitle}
          onConfirm={this.onConfirmHandler}
        >
          <SettingGPTRobotViewName
            ref="SettingGPTRobotViewName"
            value={this.nameValue}
            onInput={this.onInputGPTRobotNameHandler}
          >
          </SettingGPTRobotViewName>
        </SettingGPTViewDialog>
        
        <SettingGPTRobotViewUrlDescriptionDialog
          ref="SettingGPTRobotViewUrlDescriptionDialog"
        >
        </SettingGPTRobotViewUrlDescriptionDialog>
        
      </div>
    )
  }
})